/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include "oled.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
typedef struct {//结构体定义
    uint8_t buffer[128];//在buffer数组中存储上位机命令
    uint8_t length;//记录有效命令长度
    uint8_t ready;//0：命令未接收完成    1：命令已准备，通知系统可以执行
} UART_Command_t;//别名
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define brea_per_min 1000//最小呼吸周期
#define brea_per_max 10000//最大呼吸周期
#define brea_per_default 3000//默认呼吸周期

#define pwm_updata_freq 100
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
volatile uint16_t led_lum = 0;  //亮度
volatile uint8_t brea_dir = 1;  //呼吸方向，1变亮，0变暗
volatile uint32_t time = 0;//上一次记录的时间

//呼吸周期控制变量
volatile uint16_t period = brea_per_default;//默认呼吸周期
volatile uint16_t brea_step = 0;//步进值

//文字飘动效果
volatile uint8_t x = 0;   
volatile int8_t dir = 1;// 文字移动方向：1向右，-1向左
volatile uint32_t text_last_time = 0;  // 文字上次移动时间

UART_Command_t uart_cmd = {0};//uart_cmd:定义的变量名    ={0}：初始化结构体中每一个变量为0
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void); //系统时钟树设置void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

void text_move_effect(void) {
    uint32_t current_time = HAL_GetTick();
    
    // 每50ms移动一次文字
    if (current_time - text_last_time >= 100) {
        text_last_time = current_time;
        
        // 更新文字位置
        x += dir;
        
        // 边界检测
        if (x >= 80) {
            x = 80;
            dir = -1; 
        } else if (x <= 0) {
            x = 0;
            dir = 1; 
        }
        
        // 显示文字
        OLED_Clear();
        OLED_ShowString(x, 18, "黄庭耀", OLED_8X16);
        OLED_Update();
    }
}

void calulate_brea_step(void){//通过更新次数机选步进值
    uint32_t updates_per_cycle = period * pwm_updata_freq / 1000;//一整个周期的更新次数
    
    uint32_t half_updates = updates_per_cycle / 2;//半个周期的更新次数
    
    if(half_updates > 0){
        brea_step = 1000 / half_updates;//计算步进值
    } else {
        brea_step = 10; // 默认值
    }
    if(brea_step < 1){//步进值至少唯一
        brea_step = 1;
    }
    
    printf("Period: %dms, Step: %d, Half updates: %u\r\n", 
           period, brea_step, half_updates);
}
void brea_effect(void){
    // 只在周期改变时重新计算步进值
    // calulate_brea_step();  // 移除此行，在周期改变时再计算
    
    static uint32_t last_period = 0;
    if(period != last_period){
        calulate_brea_step();
        last_period = period;
    }//定义“周期”，避免一个周期内重复计算步进值
    
    if(brea_dir == 1){
        if(led_lum + brea_step >= 1000){
            led_lum = 1000;
            brea_dir = 0;
        }else{
            led_lum += brea_step;
        }
    }else if(led_lum <= brea_step){
            led_lum = 0;
            brea_dir = 1;
        }else{
            led_lum -= brea_step;
      }
    
    
    __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,led_lum);
}

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
static uint8_t uart1_tx_busy = 0;

// 重定向printf到USART1（轮询方式）
int fputc(int ch, FILE *f) {
    // 等待发送空闲（若DMA或其他发送操作正在进行，则阻塞等待）
    while (uart1_tx_busy);
    
    // 标记发送忙碌
    uart1_tx_busy = 1;
    
    // 轮询发送单个字符（超时100ms）
    HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 100);
    
    // 发送完成，标记空闲
    uart1_tx_busy = 0;
    
    return ch;
}


//设置呼吸值
void brea_per_set(uint16_t per_ms){
    if(per_ms < brea_per_min){
        per_ms = brea_per_min;
        printf("Warning: Period too small, set to minimum: %d ms\r\n", brea_per_min);
    }
    if(per_ms > brea_per_max){
        per_ms = brea_per_max;
        printf("Warning: Period too large, set to maximum: %d ms\r\n", brea_per_max);
    }//防止呼吸值设置过大或过小
    
    period = per_ms;
    calulate_brea_step();
    printf("Breath period set to: %d ms\r\n", period);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
    if(huart->Instance == USART1){
        uint8_t received_char = uart_cmd.buffer[uart_cmd.length - 1];
        
        // 检查是否是命令结束符
        if(received_char == '\r' || received_char == '\n'){
            uart_cmd.ready = 1;
            // 不继续接收，等待命令处理
            return;
        }
        
        // 检查缓冲区是否已满
        if(uart_cmd.length < sizeof(uart_cmd.buffer) - 1){
            // 继续接收下一个字符
            HAL_UART_Receive_IT(&huart1, &uart_cmd.buffer[uart_cmd.length], 1);
            uart_cmd.length++;
        } else {
            // 缓冲区满，标记命令就绪（即使没有结束符）
            uart_cmd.ready = 1;
        }
    }
}
void uart_command(void){
    if(uart_cmd.ready){//命令就绪就进入函数
        uint8_t cmd_length = uart_cmd.length;
        for(int i = 0; i < uart_cmd.length; i++){
            if(uart_cmd.buffer[i] == '\r' || uart_cmd.buffer[i] == '\n'){//直到第一个回车或换行符就停止，计算长度
                cmd_length = i;//赋值命令长度
                break;
            }
        }
        
        uart_cmd.buffer[cmd_length] = '\0';
        
        printf("Received: %s\r\n", uart_cmd.buffer);//确认命令
        
        // 解析 "period x" 命令
        char *cmd_str = (char*)uart_cmd.buffer;
        
        // 查找 "period" 关键字
        char *period_keyword = strstr(cmd_str, "period");
        if(period_keyword != NULL){
            char *number_start = period_keyword + 6;//跳过period
            while(*number_start == ' '){
                number_start++;
            }//跳过空格
            if(*number_start >= '0' && *number_start <= '9'){
                uint16_t new_period = atoi(number_start);
                brea_per_set(new_period);
            } else {
                printf("Error: No number found after 'period'\r\n");
            }// 解析数字
        } 
        // 解析 "getperiod" 命令
        else if(strstr(cmd_str, "getperiod") != NULL){
            printf("Current breath period: %d ms\r\n", period);
        }
        else {
            printf("Unknown command. Use 'period x' or 'getperiod'\r\n");
        }
        
        // 重置命令状态
        uart_cmd.ready = 0;
        uart_cmd.length = 0;
        
        // 重新启动接收
        HAL_UART_Receive_IT(&huart1, uart_cmd.buffer, 1);
        uart_cmd.length = 1;
    }
}

#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();//完成HAL库的基础运行环境的配置

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  //初始化GPIO、DMA、TIM2、USART1、I2C1
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_TIM2_Init();
  MX_USART1_UART_Init();
  MX_I2C1_Init();
  /* USER CODE BEGIN 2 */

    uart_cmd.length = 0;
    uart_cmd.ready = 0;
    //文字飘动初始化
    x = 0;
    dir = 1;
    OLED_Clear();
    

  HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_1);//启动PWM输出

  __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,0);//将初始PWM占空比设置为0
  time = HAL_GetTick();//获取从程序启动到当前经过的时间（毫秒数）

  calulate_brea_step();

  HAL_UART_Receive_IT(&huart1,uart_cmd.buffer,1);
  uart_cmd.length = 1;

  	OLED_Init();
    OLED_ShowString(48, 0, "From", OLED_8X16);
    OLED_ShowString(28, 18, "Happy-yao", OLED_8X16);
	OLED_Update();
	HAL_Delay(3000);
	OLED_Clear();
    OLED_ShowString(40, 18, "黄庭耀", OLED_8X16);
	OLED_Update();
	HAL_Delay(3000);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
    uint32_t now_time = HAL_GetTick();
    if(now_time - time >= (1000 / pwm_updata_freq)){//每十毫秒更新一次
      time = now_time;
      uart_command();
      
      brea_effect();

    }

    text_move_effect();
    /* USER CODE BEGIN 3 */
  }
/*OLED初始化*/

	

}
/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
